/*
*updateBy TernWii
*updateDate 2017/6/29
*for autotest public fun
*/
var onAutoTest=true;
var testServerPath='http://192.168.59.197/ctr-autotest/';
window.auto={
	modulServer:'http://consoleproject-test.sxiaobao.com/',
	reportUrl:'./report.html',
	onstep:0,
	testSpeed:100,
	testfuns:[],
	addModule:function(){},
	saveNoResponses:function(){},
	saveModelName:function(){},
	showStorage:function(){},
	showReport:function(){},
	showInfo:function(){},
	showStep:function(){},
	goNext:function(url){},
	go:function(){},
	rerun:function(){}
}
var laststep=-1;
var testcode,timeor=0;
var noresponses=[];
var onhref=window.location.href;
if(onhref.indexOf('login.html')>-1){
	testcode=new Date().getTime();
	sessionStorage.setItem('testcode',testcode);
}

//if(!onAutoTest)return;
console.log('-----------------------auto test mode '+testcode+'-------------------------------------------------------begin');
/*
*判断哪些请求返回时可以进入下一步
*/
function goStepAfterReq(_url){
	var urls=[
	]
	if(urls.indexOf(_url)>-1)
		window.auto.onstep++;
}
!function (ob) {
    ob.hookAjax = function (funs) {
        window._ahrealxhr = window._ahrealxhr || XMLHttpRequest
        XMLHttpRequest = function () {
            this.xhr = new window._ahrealxhr;
            for (var attr in this.xhr) {
                var type = "";
                try {
                    type = typeof this.xhr[attr]
                } catch (e) {}
                if (type === "function") {
                    this[attr] = hookfun(attr);
                } else {
                    Object.defineProperty(this, attr, {
                        get: getFactory(attr),
                        set: setFactory(attr)
                    })
                }
            }
        }

        function getFactory(attr) {
            return function () {
                return this.hasOwnProperty(attr + "_")?this[attr + "_"]:this.xhr[attr];
            }
        }

        function setFactory(attr) {
            return function (f) {
                var xhr = this.xhr;
                var that = this;
                if (attr.indexOf("on") != 0) {
                    this[attr + "_"] = f;
                    return;
                }
                if (funs[attr]) {
                    xhr[attr] = function () {
                        funs[attr](that) || f.apply(xhr, arguments);
                    }
                } else {
                    xhr[attr] = f;
                }
            }
        }

        function hookfun(fun) {
            return function () {
                var args = [].slice.call(arguments)
                if (funs[fun] && funs[fun].call(this, args, this.xhr)) {
                    return;
                }
                return this.xhr[fun].apply(this.xhr, args);
            }
        }
        return window._ahrealxhr;
    }
    ob.unHookAjax = function () {
        if (window._ahrealxhr)  XMLHttpRequest = window._ahrealxhr;
        window._ahrealxhr = undefined;
    }
}(window)
//}(module.exports)
function saveReport(info){
	var infos=sessionStorage.getItem('autotest');
	infos=infos?infos:'';
	infos+=info;
	sessionStorage.setItem('autotest',infos);
}
function deleUrl(url){
	for(var i=0;i<noresponses.length;i++){
		if(url==noresponses[i]){
			noresponses[i]='';
			break;
		}
	}
}

window.auto.saveNoResponses=function(){
	var infos='异常请求:<br>';
	var len=noresponses.length;
	var str='';
	for(var i=0;i<len;i++){
		if(noresponses[i]!=''){
			str+=noresponses[i]+'<br>';
		}
	}
	if(str=='')
		str+='0<br>';
	infos+=str;
	saveReport(infos);
}
window.auto.saveModelName=function(name){
	var infos=sessionStorage.getItem('autotest');
	infos=infos?infos:'';
	infos+='<strong>模块['+name+']</strong><br>';
	sessionStorage.setItem('autotest',infos);
	//alert(sessionStorage.getItem('autotest'));
}
window.auto.showStorage=function(key){
	return sessionStorage.getItem(key);
}
window.auto.showInfo=function(text){
	console.log(text);
}
window.auto.showStep=function(){
	console.log('onstep:'+window.auto.onstep);
}
window.auto.showReport=function(){
	window.auto.showInfo('++++++++++++++++++++auto test End reports:++++++++++++++++++++++++++++++++');
	//console.log('测试'+window.auto.showStorage('testcode')+':<br>'+window.auto.showStorage('autotest'));
	$("#contentIframe").contents().find("body").append("<div>"+'测试'+window.auto.showStorage('testcode')
	+':<br>'+window.auto.showStorage('autotest')+"</div>");
}
window.auto.goNext=function(url){
	if($("#contentIframe").length>0)
		$("#contentIframe").attr('src',url);
	else
		location.href=url;
}
window.auto.go=function(){
	window.auto.onstep++;
}
window.auto.rerun=function(){
	window.auto.testSpeed=100;
}
hookAjax({
//拦截回调
onreadystatechange:function(xhr){
	//console.log("onreadystatechange called: %O",xhr)
	console.log("onreadystatechange called: %s",xhr.responseURL);
	deleUrl(xhr.responseURL);
	window.auto.onstep++;
},
onload:function(xhr){
	//console.log("onload called: %O",xhr);
	console.log("onload called: %s",xhr.responseURL);
	deleUrl(xhr.responseURL);
	window.auto.onstep++;
},
onerror:function(xhr){
	//console.log("onerror called: %O",xhr);
	//console.log(JSON.stringify(xhr));
	window.auto.onstep++;
},
//拦截函数
open:function(arg){
	console.log("open called: method:%s,url:%s,async:%s",arg[0],arg[1],arg[2]);
	noresponses.push(arg[1]);
}
})

// 动态加载js脚本文件
function loadScript(doc,url){
	var oHead = doc.getElementsByTagName('HEAD').item(0); 
	var oScript= doc.createElement("script"); 
	oScript.type = "text/javascript";
	oScript.onload=function(){
		//alert(url);
	}
	oScript.src=url+"?id="+new Date().getTime(); 
	oHead.appendChild(oScript); 
}
/*
*模块化加载
*/
window.auto.atModule=function(href,html,moduleTestFun,jsFile){
	var newhref=href;
	if(newhref=='iframe')newhref=$("#contentIframe").attr('src');
	if(!newhref||html=='nothing'){
		if(!moduleTestFun){
			loadScript(document,jsFile);
			timeor=-100;
			laststep=-1;
			window.auto.onstep=0;
			window.auto.testSpeed=0;
		}
		else moduleTestFun();
		return true;
	}
	else{
		if(newhref.indexOf(html)>-1){
			if(!moduleTestFun){
				loadScript(document,jsFile);
				timeor=-100;
				laststep=-1;
				window.auto.onstep=0;
				window.auto.testSpeed=0;
			}
			else moduleTestFun();
			return true;
		}
		else return false;
	}
	
}
/*循环检测是否执行下一步*/
var ModuleTests={
	report_js:testServerPath+'module/auto-report.js',
	login_js:testServerPath+'module/auto-login.js',
	workType_js:testServerPath+'module/auto-worktype.js',
	teamType_js:testServerPath+'module/auto-teamtype.js',
	other_js:testServerPath+'module/auto-other.js'
}
window.run=function(){
	var tophref=window.location.href;
	//console.log(tophref);
	/*自动化测试模块配置*/
	if(!window.auto.atModule(tophref,'report.html',typeof(report_test)=='function'?report_test:null,ModuleTests.report_js))
	if(!window.auto.atModule(tophref,'login.html',typeof(login_test)=='function'?login_test:null,ModuleTests.login_js))
	if(!window.auto.atModule('iframe','workType.html',typeof(workType_test)=='function'?workType_test:null,ModuleTests.workType_js))
	if(!window.auto.atModule('iframe','teamType.html',typeof(teamType_test)=='function'?teamType_test:null,ModuleTests.teamType_js))
		window.auto.atModule('iframe','nothing',typeof(nothing_test)=='function'?nothing_test:null,ModuleTests.other_js);
	
	timeor+=window.auto.testSpeed;
	//console.log('onstep：'+window.auto.onstep);
	if(timeor%3000==0){
		timeor=0;
		if(window.auto.onstep!=laststep){
			//$(".running").html(onstep+'&nbsp;');
			console.log('onstep:'+window.auto.onstep)+console.log(' step:'+typeof(window.auto.testfuns[window.auto.onstep]));
			laststep=window.auto.onstep;
			if(window.auto.testfuns[window.auto.onstep])window.auto.testfuns[window.auto.onstep]();
		}
		else{
			timeor-=window.auto.testSpeed;
		}
	}
}
window.setInterval("window.run()",100);
/*
*控制栏部分
*/
function toggleBar(){
	$(".test-bar").toggle();
	if($(".bar-btn").text()=='》')
		$(".bar-btn").text('《');
	else
		$(".bar-btn").text('》');
}
function testStop(){
	window.auto.testSpeed=0;
}
function testStart(){
	window.auto.testSpeed=100;
}
function testEnd(){
	goNext(reportUrl);
}
addConsoleBar();
function addConsoleBar(){
	return;
	$("body").append("<div style='position:absolute;top:200px;right:0;width:200px;height:80px;cursor:pointer;'>"
	+"<span class='bar-btn' style='display:block;width:20px;height:40px;float:right;color:#ddd;margin-left:10px;' onclick='toggleBar()'>》</span>"
	+"<span class='test-bar' style='display:block;width:170px;float:right;text-align:right;'><div class='btn-group'><span class='running' style='color:#f30;'>0&nbsp;</span>"
	+"<button class='btn' onclick='testStop()'>暂停</button><button class='btn' onclick='testStart()'>运行</button><button class='btn' onclick='testEnd()'>终止</button>"
	+"</div></span></div>");
}
//-----------------------------------------------------------------------------------------------------------test end